/**
 * 
 */
package org.wangh.csv.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.wangh.csv.functions.ImportFromFile;
import org.wangh.csv.gui.SheetView;

/**
 * @author wang
 *
 */
public class ImportFileHandler extends AbstractHandler {
	
	private Shell shell;
	

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
		String path = dialog.open();
		
		ImportFromFile in = new ImportFromFile(path, '|');
		in.run();
		
		try {
			IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.wangh.csv.view.sheet");
			if(viewPart instanceof SheetView){
				SheetView view = (SheetView) viewPart;
				view.updateView(in.getFileName(), in.getResult());
			}
		} catch (PartInitException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	private Shell getShell(){
		if(shell == null){
			shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		}
		return shell;
	}
	
}
